//Jquery mobiles equivalent to $(document).ready(fn());
$('div:jqmData(role="page")').live('pagebeforeshow',function(){
    $("#submit_login").click(function(){
		$.mobile.showPageLoadingMsg();
        $.post(getBaseURL()+"login/doLogin",{
            username: $("#username").val(),
            password: $('#password').val()
        },function(data){	
			$.mobile.hidePageLoadingMsg();
			if (data == 'good'){	
				homeScreen();
			}
			else{
				alert(data);
				$('#password').val("");
			}
        })
    });
	
	$("#login_form").submit(function(event){
		event.preventDefault();
	});

    $("#submit_changepass").click(function(){
		$.mobile.showPageLoadingMsg()
        $.post(getBaseURL()+"settings/changePassword",{
            oldpassword: $('#oldpassword').val(),
            newpassword1: $('#newpassword1').val(),
            newpassword2: $('#newpassword2').val(),
			},function(data){
				$.mobile.hidePageLoadingMsg();
				if (data == 'good'){
					alert("Password Successfully Changed");
					window.location = getBaseURL()+'settings';
				}
				else{
					alert("Error Changing Password");
					location.reload();
				}
			});
    });

	
	
	$("#submit_feedback").click(function(){
		if ($.trim($("#feedback").val()) == ""){
			alert("Feedback form empty");
			$("#feedback").val("");
			return;
		}
		$.mobile.showPageLoadingMsg();
        $.post(getBaseURL()+"feedback/sendFeedback",{
            feedback: $("#feedback").val()
        },function(data){
			$.mobile.hidePageLoadingMsg();
            alert(data);
			location.reload();
        })
    });
});


$(document).delegate('#opendialog', 'click', function() {
	// NOTE: The selector can be whatever you like, so long as it is an HTML element.
	//       If you prefer, it can be a member of the current page, or an anonymous div
	//       like shown.
	$('<div>').simpledialog2({
	  mode: 'button',
	  headerText: 'Order a Meal',
	  headerClose: true,
	  buttonPrompt: 'Leave a Comment if you so desire',
	  buttonInput: true,
	  buttons : {
		'OK': {
		  click: function () { 
			$('#buttonoutput').text($.mobile.sdLastInput);
		  }
		},
	  }
	})
  })
  
function voteTonight(elem){
	if ($.trim($(elem).html()) == "Voted"){
		alert("You have already voted for this meal");
		return;
	}
	$.mobile.showPageLoadingMsg();
	var meal_id = $(elem).attr('value');
	$.post(getBaseURL()+"meals/buttonPressed",{
	meal_id: meal_id,
	type: 'vote'
	}, function(data){
		$.mobile.hidePageLoadingMsg();
		if(data=="good"){
			setVoted(elem);
		}
		else if(data=="fail"){
			alert("A server error occurred, please try again soon.");
		}
		else if (data=="time"){
			alert("The cutoff time for meal ordering has passed.");
			location.reload();
		}
		else {
			data = "Warning: This meal contains " + data +  ". Do you want to proceed?";
		
			answer = confirm(data)
			if(answer) {
				$.mobile.showPageLoadingMsg();
				$.post(getBaseURL()+"meals/forceChoice",{
				meal_id: meal_id,
				type: 'vote'
				},function(data2) {
					$.mobile.hidePageLoadingMsg();
					if(data2=="good") {
						setVoted(elem);
					}
					else {
						alert("A server error occurred, please try again soon.");
					}
				});
			}
		}
	});
}


function orderTonight(elem){
	if ($.trim($(elem).html()) == "Ordered"){
		alert("You have already ordered this meal");
		return;
	}
	var meal_id = $(elem).attr('value');
	var comment = prompt("Enter meal comment (150 chars)");
	
	if (comment == null){
		return;
	}
	
	
	$.mobile.showPageLoadingMsg();
	$.post(getBaseURL()+"meals/buttonPressed",{
	meal_id: meal_id,
	type: 'order',
	comment: comment
	}, function(data){
		$.mobile.hidePageLoadingMsg();
		if(data=="good"){
			setOrdered(elem);
		}
		else if(data=="fail"){
			alert("A server error occurred, please try again soon.");
		}
		else if (data=="time"){
			alert("The cutoff time for meal ordering has passed.");
			location.reload();
		}
		else {
			data = "Warning: This meal contains " + data +  ". Do you want to proceed?";
		
			answer = confirm(data)
			if(answer) {
				$.mobile.showPageLoadingMsg();
				$.post(getBaseURL()+"meals/forceChoice",{
				meal_id: meal_id,
				type: 'order',
				comment: comment
				},function(data2) {
					$.mobile.hidePageLoadingMsg();
					if(data2=="good") {
						setOrdered(elem);
					}
					else {
						alert("A server error occurred, please try again soon.");
					}
				});
			}
		}
	});
}

function setVoted(elem){
console.log($("button.vote"));
	$("button.vote").each(function(){
		$(this).text("Vote");
		$(this).prev('span').find('.ui-btn-text').text("Vote");
	});
	if (elem != null){
		$(elem).text("Voted");
		$(elem).prev('span').find('.ui-btn-text').text("Voted");
		alert("Thanks for voting.");
	}
}

function setOrdered(elem){
console.log($("button.order"));
	$("button.order").each(function(){
		$(this).text("Order");
		$(this).prev('span').find('.ui-btn-text').text("Order");
	});
	if (elem != null){
		$(elem).text("Ordered");
		$(elem).prev('span').find('.ui-btn-text').text("Ordered");
		alert("Your meal has been successfully ordered.");
	}
}

function saveAllergies(){
	var allergies = [];
	$.mobile.showPageLoadingMsg();
	$(".allergy_check").each(function(){
		if ($(this).attr('checked')){
			allergies.push($(this).attr('name'));
		}
	});
	
	$.post(getBaseURL()+"settings/saveAllergies",{
		allergies: allergies
	}, function(data){
		$.mobile.hidePageLoadingMsg();
		if (data == 'good'){
			alert('Dietary requirements saved');
		}
		else{
			alert(data);
		}
		window.location = getBaseURL()+"/settings";
	});
}

function doCancelVote(){
	if (!confirm("This will remove your current vote for today from the system. Continue?")){
		return;
	}
	$.mobile.showPageLoadingMsg();
	$.post(getBaseURL()+"settings/cancelVote",{}, function(data){
		$.mobile.hidePageLoadingMsg();
		if (data == "good"){
			alert('Your vote has been cancelled');
		}
		else{
			alert(data);
		}
	});
}

function doCancelOrder(){
	if (!confirm("This will remove your current order today from the system. Continue?")){
		return;
	}
	$.mobile.showPageLoadingMsg();
	$.post(getBaseURL()+"settings/cancelOrder",{}, function(data){
		$.mobile.hidePageLoadingMsg();
		if (data == "good"){
			alert('Your order has been cancelled');
		}
		else{
			alert(data);
		}
	});
}


function homeScreen(){
	window.location = getBaseURL()+'meals';
}




















